import Vue from "vue";//引入vue核心
import { filter } from "vue/types/umd";
import Vuex from "vuex";//引入状态机核心

Vue.use(Vuex);//在vue中注入vuex

export default new Vuex.Store({
	
	//仓库数据本身
  state: {
    //商品列表
    goodsList: [{ foods: [{ num: 0, id: 0 }] }]

  },
  
  
  //修改仓库数据的唯一方式
  mutations: {
    //函数修改-->参数一：state仓库数据，参数二：形参，接收数据
    getgoodslist(state, val) {
      state.goodsList = val;
    },
    clearData(state) {
      for (const obj of state.goodsList) {
        for (const val of obj.foods) {
          val.num = 0;
        }
      }
    },
    countFood(state, val) {
      for (const obj of state.goodsList) {
        for (const item of obj.foods) {
          if (item.id == val.id) {
            item.num += val.n;
          }
        }
      }
    }

  },
  
  
  //仓库中的计算属性
  getters: {
    //传递一个参数state
    //过滤 goodsList.foods.num>0的foods
    filterfoods(state) {
      const arr: any = [];
      for (const obj of state.goodsList) {
        for (const val of obj.foods) {
          if (val.num > 0) {
            arr.push(val)
          }
        }
      }
      return arr;
    },
    filterFlag(state) {
      let flag = true;
      for (const obj of state.goodsList) {
        for (const val of obj.foods) {
          if (val.num > 0) {
            flag = false;
          }
        }
      }
      return flag;
    }
  },
  
  
  actions: {},//异步修改仓库数据，最终还是通过mutations来修改
  modules: {},//合并状态机
});
